package com.jk.framework.config;

import cn.hutool.core.net.NetUtil;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator;
import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.jk.framework.mybatis.handlers.BaseMetaObjectHandler;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@EnableTransactionManagement(proxyTargetClass = true)
@Configuration
@MapperScan("${mybatis-plus.mapperPackage}")
//@MapperScan("com.unte.mes.**.mapper")
public class MyBatisPlusConfig {
   /* @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer configurer = new MapperScannerConfigurer();
        configurer.setBasePackage("com.unte.mes.**.mapper");
        return configurer;
    }*/

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();

        mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());

        mybatisPlusInterceptor.addInnerInterceptor(paginationInnerInterceptor());

//        mybatisPlusInterceptor.addInnerInterceptor(new PlusDataPermissionInterceptor());
        return mybatisPlusInterceptor;
    }


    /**
     * 分页插件，自动识别数据库类型
     */
    public PaginationInnerInterceptor paginationInnerInterceptor() {
        PaginationInnerInterceptor interceptor = new PaginationInnerInterceptor(DbType.MYSQL);
        // 设置最大单页限制数量，默认 500 条，-1 不受限制
        interceptor.setMaxLimit(-1L);
        interceptor.setOptimizeJoin(false);
        // 分页合理化
//        interceptor.setOverflow(true);
        return interceptor;
    }

        /**
         * 元对象字段填充控制器
         */
        @Bean
        public MetaObjectHandler metaObjectHandler() {
            return new BaseMetaObjectHandler();
        }

        /**
         * 使用网卡信息绑定雪花生成器
         * 防止集群雪花ID重复
         */
        @Bean
        public IdentifierGenerator idGenerator() {
            return new DefaultIdentifierGenerator(NetUtil.getLocalhost());
        }
}